var fotoramaDiv = null;
var lastSearchKey = '';
var aLoadedSearchTab = [];
$(document).ready(function() {
	scrollTop();
	lazyLoadImage('img.product-item.lazy', '.product-image-wrapper');
	lazyLoadImage('img.post-item.lazy', 'div.media');
	lazyLoadImage('img.sticky-item.lazy', 'div.media');
	lazyLoadImage('img.shop-item.lazy', '.product-image-wrapper');
	initCommonFunction();
	initCart();
	searchform();
	sendContact();
	sendContactAdvertise();
	getShopCategoryCount();
	fotoramaSlide();
	updateCartItemByControl();
	billing();
	addFancyForExtendedImage();
	countRaoVat();
	imgPreview();
	changeTabPane();
	setDatePicker();
});
function makeToast(message, code) {
	var icon = 'fa fa-times';
	var m_class = 'error';
	var bg_class = {'success': '#dff0d8','error': '#f2dede'};
	if (code == 1) {
		icon = 'fa fa-check-circle';
		m_class = 'success';
	}
	$('#toast .toast-state i').removeClass().addClass(icon);
	$('#toast .toast-message').html(message);
	$('#toast').show().removeClass().addClass('fadeInUp animated').one('webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend', function() {
		$(this).removeClass();
		setTimeout(function() {
			$('#toast .toast-close').click();
		}, 1000);
	});
	$('#toast .toast-close').click(function() {
		$('#toast').removeClass().addClass('fadeOutUp animated').one('webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend', function() {
			$(this).removeClass();
			$(this).hide();
		});
	});
}
function scrollTop() {
	$(function() {
		$.scrollUp({scrollName: 'scrollUp',scrollDistance: 300,scrollFrom: 'top',scrollSpeed: 300,easingType: 'linear',animation: 'fade',animationSpeed: 200,scrollTrigger: false,scrollText: '<i class="fa fa-angle-up"></i>',scrollTitle: false,scrollImg: false,activeOverlay: false,zIndex: 2147483647});
	});
}
function lazyLoadImage(element, parent) {
	$(element).viewportChecker({classToAdd: 'visible',classToRemove: 'invisible',offset: 100,invertBottomOffset: true,repeat: false,scrollHorizontal: false,callbackFunction: function(elem, action) {
		elem.attr({src: elem.attr('data-src')}).css('height', 'auto').removeClass('lazy').removeAttr('data-src').parents(parent);
	}});
}
function sendContactAdvertise() {
	$('.btn-send-contact-ad').click(function() {
		var form = $(this).closest('form');
		form.ajaxForm({beforeSend: function() {
			toggleProgressModal(true);
		},complete: function(xhr) {
			toggleProgressModal(false);
			form.find('input[name=userfile]').val('');
			setMessage($.parseJSON(xhr.responseText));
			htmlScrollToMessage();
		}});
	});
}
function searchTab(frmSearch) {
	$.ajax({url: frmSearch.attr('data-search-tab'),data: frmSearch.serialize(),type: frmSearch.attr('method'),cache: false,success: function(data) {
		$('#content-center').html(data);
	}});
}
function searchform() {
	var frmSearch = $('#frm-search');
	frmSearch.submit(function(e) {
		e.preventDefault();
		$('#btn-search').click();
		return false;
	});
	$('#btn-search').click(function() {
		var skey = $('#search-box').val();
		var scase = frmSearch.find('#search-case').val();
		if (skey != lastSearchKey) {
			searchTab(frmSearch);
			$.ajax({url: frmSearch.attr('action'),type: frmSearch.attr('method'),data: frmSearch.serialize(),cache: false,beforeSend: function() {
				toggleProgressModal(true);
			},success: function(data) {
				document.title = "TÃ¬m kiáº¿m | PhiÃªn Chá»£ Viá»‡t";
				window.history.replaceState("State", "Title", frmSearch.attr('action') + "?" + frmSearch.serialize());
				$('#search-tab-content' + ' #' + scase).html(data);
				lazyLoadImage('img.product-item.lazy', '.product-image-wrapper');
				toggleProgressModal(false);
				aLoadedSearchTab.push(scase);
				htmlScrollTo('#content-center');
			}});
			lastSearchKey = skey;
			aLoadedSearchTab = [];
		}
	});
	$(document.body).on('click', '#search-tab a[data-toggle="tab"]', function(e) {
		e.preventDefault;
		var scase = $(this).attr("data-case");
		frmSearch.find('#search-case').val(scase);
		if (aLoadedSearchTab.indexOf(scase) == -1) {
			frmSearch.find('#search-case').val(scase);
			$.ajax({url: frmSearch.attr('action'),type: frmSearch.attr('method'),data: frmSearch.serialize(),cache: false,beforeSend: function() {
				toggleProgressModal(true);
			},success: function(data) {
				window.history.replaceState("State", "Title", frmSearch.attr('data-action') + '?' + frmSearch.serialize());
				$('#search-tab-content' + ' #' + scase).html(data);
				lazyLoadImage('img.product-item.lazy', '.product-image-wrapper');
				toggleProgressModal(false);
				aLoadedSearchTab.push(scase);
			}});
		}
	});
	$(document.body).on('click', '.search-paging ul.pagination li a', function(e) {
		e.preventDefault();
		var ele = $(this);
		if (ele.attr('href') == '#') {
			return;
		}
		$.ajax({url: ele.attr('href'),type: frmSearch.attr('method'),data: frmSearch.serialize(),cache: false,beforeSend: function() {
			toggleProgressModal(true);
		},success: function(data) {
			window.history.replaceState("State", "Title", ele.attr('href'));
			var scase = frmSearch.find('#search-case').val();
			$('#search-tab-content' + ' #' + scase).html(data);
			lazyLoadImage('img.product-item.lazy', '.product-image-wrapper');
			toggleProgressModal(false);
		}});
		return false;
	});
}
function getShopCategoryCount() {
	var needCountShop = $('.need-get-shop-cate');
	if (needCountShop.length > 0) {
		var aItems = {'item': {}};
		needCountShop.each(function(i, j) {
			var item = $(this);
			aItems['item'][item.attr('data-item')] = item.attr('data-id');
		});
		$.ajax({url: $('#shop-category-list').attr('data-count'),type: 'POST',data: aItems,cache: false,success: function(data) {
			console.log(data);
		}});
	}
}
function fotoramaSlide() {
	if (jQuery().fotorama != undefined) {
		fotoramaDiv = $('.fotorama').fotorama({width: 700,maxwidth: '100%',ratio: 16 / 9,allowfullscreen: true,nav: 'thumbs',captions: true,show: $(this).attr('data-start-index'),}).on('fotorama:show', function(e, fotorama, extra) {
			var option = selectedInSet.find('option[data-index=' + fotorama.activeIndex + ']');
			selectedInSet.val(option.val());
			changeSelectedProduct(option);
		});
		var selectedInSet = $('select#product-temp-detail');
		selectedInSet.change(function() {
			var option = $(this).find('option:selected');
			fotoramaDiv.data('fotorama').show({index: option.attr('data-index'),time: 0});
		});
		$('#product-qty').change(function() {
			var option = selectedInSet.find('option:selected');
			calculateOrderValue(option);
		});
	}
}
function changeSelectedProduct(option) {
	$('#product-id').val(option.val());
	$('#product-price').val(option.attr('data-price'));
	$('#order-temp-price').html(option.attr('data-price-format'));
	$('#order-temp-price-old').html(option.attr('data-price-old-format'));
	$('.product-description').addClass('hidden');
	$('.description-' + option.val()).removeClass('hidden');
	calculateOrderValue(option);
}
function calculateOrderValue(option) {
	var val = $('#product-qty').val() * option.attr('data-price');
	if (!isNaN(val)) {
		$('#order-temp-value').html(formatCurrency(val));
	} else {
		$('#order-temp-value').html('');
	}
}
function updateCartItemByControl() {
	$('.cart_quantity_control').click(function(e) {
		e.preventDefault();
		var cart = {box: $($(this).parents('.cart_quantity_button').attr('data-follow')),control: $(this),dvalue: $(this).attr('data-value'),btn: $($(this).parents('.cart_quantity_button').attr('data-submit'))}
		var box_value = eval(cart.box.val() + cart.dvalue);
		if (box_value != 0) {
			cart.box.val(box_value);
		}
		cart.btn.click();
		return false;
	});
	$('.item-quantity').keydown(function(e) {
		var val = $(this).val();
		if (e.which == 13) {
			$($(this).parents('.cart_quantity_button').attr('data-submit')).click();
		}
		if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110, 190]) !== -1 || (e.keyCode == 65 && e.ctrlKey === true) || (e.keyCode >= 35 && e.keyCode <= 40)) {
			return;
		}
		if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
			e.preventDefault();
		}
	});
}
function billing() {
	$('#order-info-same').change(function() {
		var ischeck = $(this).is(':checked');
		$('#form-receiver input').attr('disabled', !ischeck);
		$('#form-receiver textarea').attr('disabled', !ischeck);
		if (ischeck) {
			$('#receiver_name').focus();
		}
	});
	$('#btn-cart-submit').click(function() {
		var btn = $(this);
		var form = $('#frm-cart');
		$.ajax({url: form.attr('action'),type: form.attr('method'),data: form.serialize(),cache: false,beforeSend: function() {
			var lastText = btn.html();
			btn.attr('data-last-text', lastText);
			btn.html("Äang gá»­i Ä‘Æ¡n hÃ ng ...");
			btn.attr('disabled', true);
		},success: function(data) {
			var msg = $('#flg_message');
			msg.removeClass('hidden');
			if (data.code == 1) {
				msg.addClass('alert-success').removeClass('alert-danger');
				resetForm('#frm-cart');
			} else {
				msg.addClass('alert-danger').removeClass('alert-success');
			}
			msg.find('.message-title').html('').html(data.title);
			msg.find('.message-text').html('').html(data.text);
			htmlScrollToMessage();
		}}).done(function() {
			btn.html(btn.attr('data-last-text'));
			btn.attr('disabled', false);
		});
	});
}
function addFancyForExtendedImage() {
	if ($('#raovat-content') != undefined) {
		$('#raovat-content img').removeAttr('style');
		var oImagePath = $('#raovat-content img').attr('src');
		var parent = $('#raovat-content img').parent();
		var oImageSrc = parent.html();
		$('#raovat-content img').remove();
		var aFancy = "<a href='" + oImagePath + "' class='fancybox'>" + oImageSrc + "</a>";
		parent.append(aFancy);
	}
}
function countRaoVat() {
	if ($('#rao-vat-page').length > 0) {
		$.ajax({url: $('#rao-vat-page').attr('data-count-url'),success: function(data) {
			$('.raovat-cate').each(function(i, j) {
				if ($(this).attr('data-cate-id') in data) {
					$(this).html(data[$(this).attr('data-cate-id')]);
				}
			});
		}});
	}
}
